<template>
	<div>
		<cus-allcard style="padding-bottom:0px" :showTitle="false">
			<div class="topBody">
				<div class="topBodyItem">
					<cus-Button class="mr_10" type="primary" @onClick="addButton" v-permission="20">添加账簿</cus-Button>
				</div>
			</div>
		</cus-allcard>
		<cus-allcard style="margin-top:20px;padding-top:24px" :showTitle="false">
			<cusTable border :loading="form.loading" :columns="columns" :data="dataList" :size="vuex_config.tableSize">
				<template slot-scope="{ row }" slot="isjiezhuan">
					<Tag color="success" v-if="row.isjiezhuan === 0">未结账</Tag>
					<Tag color="error" v-if="row.isjiezhuan === 1">已结账</Tag>
				</template>

				<template slot-scope="{ row }" slot="operation">
					<div class="flex">
						<cus-button type="text" size="small" style="color:#1E6FFF;padding:0 8px;"
							@onClick="tableIsHandoverButtton(row)">
							交接记录
						</cus-button>
						<cus-button type="text" size="small" style="color:#1E6FFF;padding:0 8px;"
							@onClick="tableBookHandoverButtton(row)">
							账簿交接
						</cus-button>
						<cus-button v-if="row.isjiezhuan === 0" type="text" size="small"
							style="color:#FF4746;padding:0 8px;" v-permission="40" @onClick="tabelDeletButton(row)">
							删除
						</cus-button>
					</div>
				</template>
			</cusTable>
			<!-- <div style="width: 100%; display: flex; justify-content: flex-end">
          <cus-page :data="pagesOne"
                    class="mt_10"
                    @pageChange="getAllSubjectApi(0)"></cus-page>
        </div> -->
		</cus-allcard>
		<cus-modal ref="Addmodal" title="添加账簿" @on-visible-change="onVisibleChange" @onOk="onOkadd" :mask-closable="true">
			<Form ref="formValidateAdd" :model="addform" :label-width="100">
				<FormItem label="账簿年度" prop="year" :rules="{
					required: true,
					message: '账簿年度不能为空',
					trigger: 'blur',
					type: 'date'
				}">
					<Date-picker @on-change="dataPickerChange(addform.year)" v-model="addform.year" type="year"
						placeholder="选择年度" style="width: 200px"></Date-picker>
				</FormItem>
				<FormItem label="单位" prop="department" :rules="{ required: true, message: '单位不能为空', trigger: 'blur' }">
					<Input v-model="addform.department" style="width: 200px" placeholder="请输入单位"></Input>
				</FormItem>
				<FormItem label="主管人" prop="manager" :rules="{
					required: true,
					message: '主管人不能为空',
					trigger: 'blur'
				}">
					<Input v-model="addform.manager" maxlength="30" style="width: 200px" placeholder="请输入主管人"></Input>
				</FormItem>

				<FormItem label="主管人职别" prop="managerrank" :rules="{
					required: true,
					message: '主管人职别不能为空',
					trigger: 'blur'
				}">
					<Input v-model="addform.managerrank" maxlength="30" style="width: 200px" placeholder="请输入主管人职别"></Input>
				</FormItem>

				<FormItem label="经管人" prop="operator" :rules="{
					required: true,
					message: '经管人不能为空',
					trigger: 'blur'
				}">
					<Input v-model="addform.operator" maxlength="30" style="width: 200px" placeholder="请输入经管人"></Input>
				</FormItem>
				<FormItem label="经管人职别" prop="operatorrank" :rules="{
					required: true,
					message: '经管人职别不能为空',
					trigger: 'blur'
				}">
					<Input v-model="addform.operatorrank" maxlength="30" style="width: 200px" placeholder="请输入经管人职别"></Input>
				</FormItem>

				<FormItem label="科目设置" prop="yearSubject" :rules="{
					required: true,
					message: '科目设置不能为空',
					trigger: 'blur'
				}">
					<Select v-model="addform.yearSubject" size="large" placeholder="请选择科目设置"
						@on-change="selectModelChange1()" style="width: 200px">
						<Option :value="0 + ''">初始化数据</Option>
						<Option v-for="item in dataList" :value="item.year + ''" :key="item.year">{{ item.year }}</Option>
					</Select>
				</FormItem>
				<FormItem label="摘要设置" prop="yearAbstract" :rules="{
					required: true,
					message: '摘要设置不能为空',
					trigger: 'blur'
				}">
					<Select v-model="addform.yearAbstract" size="large" placeholder="请选择摘要设置"
						@on-change="selectModelChange2()" style="width: 200px">
						<Option :value="0 + ''">初始化数据</Option>
						<Option v-for="item in dataList" :value="item.year + ''" :key="item.year">{{ item.year }}</Option>
					</Select>
				</FormItem>
			</Form>
		</cus-modal>
		<cus-modal ref="bookHandoverModal" title="账簿交接" @on-visible-change="bookHandoverChange" @onOk="okBookHandover"
			:mask-closable="true">
			<Form ref="formBookHandover" :model="bookHandoverForm" :label-width="100">
				<FormItem label="新主管人" prop="afterManager" :rules="{
					required: true,
					message: '新主管人不能为空',
					trigger: 'blur'
				}">
					<Input v-model="bookHandoverForm.afterManager" style="width: 200px" maxlength="30"
						placeholder="请输入新主管人"></Input>
				</FormItem>

				<FormItem label="新主管人职别" prop="afterManagerRank" :rules="{
					required: true,
					message: '新主管人职别不能为空',
					trigger: 'blur'
				}">
					<Input v-model="bookHandoverForm.afterManagerRank" style="width: 200px" maxlength="30"
						placeholder="请输入新主管人职别"></Input>
				</FormItem>

				<FormItem label="新经管人" prop="afterOperator" :rules="{
					required: true,
					message: '新经管人不能为空',
					trigger: 'blur'
				}">
					<Input v-model="bookHandoverForm.afterOperator" style="width: 200px" maxlength="30"
						placeholder="请输入新经管人"></Input>
				</FormItem>
				<FormItem label="新经管人职别" prop="afterOperatorRank" :rules="{
					required: true,
					message: '新经管人职别不能为空',
					trigger: 'blur'
				}">
					<Input v-model="bookHandoverForm.afterOperatorRank" style="width: 200px" maxlength="30"
						placeholder="请输入新经管人职别"></Input>
				</FormItem>
				<FormItem label="交接单位" prop="afterDepartment" :rules="{
					required: true,
					message: '交接单位不能为空',
					trigger: 'blur'
				}">
					<Input v-model="bookHandoverForm.afterDepartment" style="width: 200px" maxlength="30"
						placeholder="请输入交接单位"></Input>
				</FormItem>
				<FormItem label="交接备注" prop="remark" :rules="{
					required: true,
					message: '交接备注不能为空',
					trigger: 'blur'
				}">
					<Input v-model="bookHandoverForm.remark" style="width: 200px" maxlength="50"
						placeholder="请输入交接备注"></Input>
				</FormItem>
			</Form>
		</cus-modal>
		<cus-modal ref="isHandoverModal" title="交接记录" width="1200" @onOk="okisHandover" :mask-closable="true">
			<template slot="footer">
				<div style="display: flex;
  justify-content:flex-end;
  align-items:center;">
					<cus-button type="primary" size="small" @onClick="okisHandover">关闭</cus-button>
				</div>
			</template>
			<Table border :loading="form.loading" :columns="columnsIsHandover" :data="isHandoverdataList" :height="isHandoverdataList.length == 0
					? '177'
					: isHandoverdataList.length * 77 + 100
				" :size="vuex_config.tableSize">
				<template slot-scope="{ row }" slot="createtime">
					{{ new Date(row.createtime).Format('yyyy-MM-dd hh:mm:ss') }}
				</template>
			</Table>
		</cus-modal>
	</div>
</template>
<script>
import {
	getAccountBookListByUser,
	deleteAccountBookByAccountbookId,
	chekckAccountBook,
	addAccountBook,
	addRecord,
	getRecordListByAccountBookId
} from '@/api/businessAccountingApi/essentialInformationApi'
// 外部新添科目功能
const addform = {
	year: null, // 账簿年度
	manager: '', // 主管人
	managerrank: '', // 主管人职别
	operator: '', // 经管人
	operatorrank: '', // 经管人职别
	department: '', // 单位
	yearSubject: 1, // 科目(0表示系统初始化科目,具体年份则年份账簿科目)
	yearAbstract: 2 // 摘要(同科目)
}
// 账簿交接功能
const bookHandoverForm = {
	afterManager: null, //	交接后主管人(30)
	afterManagerRank: null, //	交接后主管人职别(30)
	afterOperator: null, //	交接后经管人(30)
	afterOperatorRank: null, //	交接后经管人职别(30)
	afterDepartment: null, //	交接后单位(30)
	remark: null //	交接备注(50)
}
export default {
	data() {
		return {
			form: {
				loading: false,
				name: '',
				startTime: '',
				endTime: ''
			},
			// 表头
			columns: [
				{
					title: '序号',
					type: 'index',
					align: 'center',
					minWidth: 50
				},
				{
					title: '年度',
					key: 'year',
					align: 'center',
					minWidth: 100
				},
				{
					title: '主管人',
					key: 'manager',
					align: 'center',
					minWidth: 100
				},
				{
					title: '主管人职别',
					key: 'managerrank',
					align: 'center',
					minWidth: 120
				},
				{
					title: '经管人',
					key: 'operator',
					align: 'center',
					minWidth: 100
				},
				{
					title: '经管人职别',
					key: 'operatorrank',
					align: 'center',
					minWidth: 120
				},
				{
					title: '账簿状态',
					slot: 'isjiezhuan',
					align: 'center',
					minWidth: 100
				},
				// {
				// 	title: '备注信息',
				// 	slot: 'remark',
				// 	align: 'center',
				// 	minWidth: 100
				// },
				{
					title: '操作',
					fixed: 'right', // 右侧固定
					slot: 'operation',
					align: 'center',
					minWidth: 200
				}
			],
			dataList: [], // 表格列表
			//交接记录 表头
			columnsIsHandover: [
				{
					title: '序号',
					type: 'index',
					align: 'center',
					minWidth: 50
				},
				{
					title: '交接前',
					align: 'center',

					children: [
						{
							title: '主管人',
							key: 'beforeManager',
							align: 'center',
							minWidth: 100
						},
						{
							title: '主管人职别',
							key: 'beforeManagerRank',
							align: 'center',
							minWidth: 120
						},
						{
							title: '经管人',
							key: 'beforeOperator',
							align: 'center',
							minWidth: 100
						},
						{
							title: '经管人职别',
							key: 'beforeOperatorRank',
							align: 'center',
							minWidth: 120
						},
						{
							title: '单位',
							key: 'beforeDepartment',
							align: 'center',
							minWidth: 120
						}
					]
				},
				{
					title: '交接后',
					align: 'center',
					children: [
						{
							title: '主管人',
							key: 'afterManager',
							align: 'center',
							minWidth: 100
						},
						{
							title: '主管人职别',
							key: 'afterManagerRank',
							align: 'center',
							minWidth: 120
						},
						{
							title: '经管人',
							key: 'afterOperator',
							align: 'center',
							minWidth: 100
						},
						{
							title: '经管人职别',
							key: 'afterOperatorRank',
							align: 'center',
							minWidth: 120
						},
						{
							title: '单位',
							key: 'afterDepartment',
							align: 'center',
							minWidth: 120
						}
					]
				},
				{
					title: '交接时间',
					slot: 'createtime',
					align: 'center',
					minWidth: 120
				},
				{
					title: '备注',
					key: 'remark',
					align: 'center',
					minWidth: 100
				}
			],
			isHandoverdataList: [], // 交接记录表格列表
			// 分页
			pages: {
				page: 1,
				pageSize: 10,
				pageTotal: 0
			},
			accountbookId: 0, // 表格所属单个id 删除接口调用
			// 添加弹框表单
			addform: addform,
			bookHandoverForm: bookHandoverForm, //账簿交接表单

		}
	},
	mounted() {

		this.getAccountBookListByUserApi() // 根据用户id查询账簿-选择器使用 接口
	},

	methods: {

		// 根据用户id查询账簿-选择器使用 接口
		getAccountBookListByUserApi() {
			this.form.loading = true
			return new Promise((resolve) => {
				getAccountBookListByUser({
					userid: this.vuex_user.base.id, // 用户id
					token: this.$store.state.vuex_user.token
				}).then((res) => {
					this.form.loading = false
					if (res.errorcode === 0) {
						this.dataList = res.accountbooklist
						resolve()
					} else {
						this.$Message.error(res.resultmsg)
					}
				})
			})
		},
		// 交接记录 接口
		getRecordListByAccountBookIdApi() {
			this.form.loading = true
			return new Promise((resolve) => {
				getRecordListByAccountBookId({
					accountBookId: this.accountbookId
				}).then((res) => {
					this.form.loading = false
					if (res.retCode === 2000) {
						this.isHandoverdataList = res.data
						resolve()
					} else {
						this.$Message.error(res.retMsg)
					}
				})
			})
		},
		// 账簿交接 接口
		addRecordApi() {

			this.form.loading = true
			return new Promise((resolve) => {
				addRecord({
					accountbookId: this.accountbookId, //账簿ID
					afterManager: this.bookHandoverForm.afterManager, //	交接后主管人(30)
					afterManagerRank: this.bookHandoverForm.afterManagerRank, //	交接后主管人职别(30)
					afterOperator: this.bookHandoverForm.afterOperator, //	交接后经管人(30)
					afterOperatorRank: this.bookHandoverForm.afterOperatorRank, //	交接后经管人职别(30)
					afterDepartment: this.bookHandoverForm.afterDepartment, //	交接后单位(30)
					remark: this.bookHandoverForm.remark //	交接备注(50)
				}).then((res) => {
					this.form.loading = false
					if (res.retCode === 0) {

						this.$refs['bookHandoverModal'].show = false //关闭账簿交接弹框
						this.$Message.success(res.retMsg)
						this.getAccountBookListByUserApi() // 根据用户id查询账簿-选择器使用 接口
						resolve()
					} else {
						console.log(2222);
						// this.$Message.error(res.retMsg)
					}
				})
			})
		},
		// 删除账簿 接口
		deleteAccountBookByAccountbookIdApi() {
			this.form.loading = true
			return new Promise((resolve) => {
				deleteAccountBookByAccountbookId({
					accountbookId: this.accountbookId,
					userid: this.vuex_user.base.id // 用户id
				}).then((res) => {
					this.form.loading = false
					if (res.errorcode === 0) {
						this.$Message.success(res.resultmsg)
						this.getAccountBookListByUserApi() // 根据用户id查询账簿-选择器使用 接口
						resolve()
					} else {
						this.$Message.error(res.resultmsg)
					}
				})
			})
		},
		// 添加账簿前校验是否存在活动账簿 接口
		chekckAccountBookApi() {
			this.form.loading = true
			return new Promise((resolve) => {
				chekckAccountBook({
					userid: this.vuex_user.base.id, // 用户id
					token: this.$store.state.vuex_user.token
				}).then((res) => {
					this.form.loading = false
					if (res.errorcode === 0) {
						if (res.flag) {
							this.$refs['Addmodal'].show = true // 开启添加科目弹框
						} else {
							this.$Message.error('存在活动账簿,不允许添加!')
						}
						resolve()
					} else {
						this.$Message.error(res.resultmsg)
					}
				})
			})
		},
		// 添加账簿 接口
		addAccountBookApi() {
			this.form.loading = true
			return new Promise((resolve) => {
				addAccountBook({
					year: new Date(this.addform.year).Format('yyyy'), // 账簿年度
					manager: this.addform.manager, // 主管人
					managerrank: this.addform.managerrank, // 主管人职别
					operator: this.addform.operator, // 经管人
					operatorrank: this.addform.operatorrank, // 经管人职别
					department: this.addform.department, // 单位
					userid: this.vuex_user.base.id, // 用户id
					yearSubject: this.addform.yearSubject, // 科目(0表示系统初始化科目,具体年份则年份账簿科目)
					yearAbstract: this.addform.yearAbstract // 摘要(同科目)
				}).then((res) => {
					this.form.loading = false
					if (res.errorcode === 0) {
						this.$refs['Addmodal'].show = false // 开启添加科目弹框
						this.getAccountBookListByUserApi() // 根据用户id查询账簿-选择器使用 接口
						this.$Message.success(res.resultmsg)
						resolve()
					} else {
						this.$Message.error(res.resultmsg)
					}
				})
			})
		},
		// 表格交接记录按钮
		tableIsHandoverButtton(valueData) {
			this.accountbookId = valueData.accountbookId // 表格所属单个id
			this.$refs['isHandoverModal'].show = true //打开交接记录弹框
			this.getRecordListByAccountBookIdApi() // 交接记录 接口
		},
		// 交接记录弹框确定按钮
		okisHandover() {
			this.$refs['isHandoverModal'].show = false //打开交接记录弹框
		},
		// 表格账簿交接按钮
		tableBookHandoverButtton(valueData) {
			this.accountbookId = valueData.accountbookId // 表格所属单个id
			this.$refs['bookHandoverModal'].show = true //打开账簿交接弹框
		},
		bookHandoverChange(v) {
			this.$refs['formBookHandover'].resetFields() //表单重置
			if (this.$refs['bookHandoverModal'].show == true) {
				//打开弹框时，给默认值
			}
		},
		// 账簿交接弹框确定按钮
		okBookHandover() {

			this.$refs['formBookHandover'].validate((valid) => {

				if (valid) {

					this.$nextTick(() => {
						this.$cu.dialog({}).then(({ }) => {
							this.addRecordApi() // 账簿交接 接口
						})
					})
				}
			})
		},
		// 表格删除按钮
		tabelDeletButton(valueData) {
			this.$cu.dialog({ params: valueData }).then(({ accountbookId }) => {
				this.accountbookId = valueData.accountbookId // 表格所属单个id
				this.deleteAccountBookByAccountbookIdApi() // 删除经费账科目或粮秣账科目 接口
			})
		},
		// 添加账簿按钮
		addButton() {
			this.chekckAccountBookApi() // 添加账簿前校验是否存在活动账簿 接口
		},
		// 弹框开启关闭变化触发
		onVisibleChange(v) {
			this.$refs['formValidateAdd'].resetFields()
			setTimeout(() => {
				if (this.$refs['Addmodal'].show == true) {
					//打开弹框时，给默认值
					// 1.账簿年度默认值：
					//  —当账簿列表为空时，默认为系统当前年度
					//  —当账簿列表不为空时，默认值为账簿年度最大值+1。

					// 2.科目设置、摘要设置默认值：
					//  —当账簿列表为空时，默认为“初始化数据”
					//  —当账簿列表不为空时，默认为账簿年度最大值。
					if (this.dataList.length > 0) {
						//账簿列表不为空时

						this.addform.yearSubject = this.dataList[0].year + '' //默认为账簿年度最大值
						this.addform.yearAbstract = this.dataList[0].year + '' //默认为账簿年度最大值

						let bigValue = this.dataList[0].year
						this.dataList.forEach((element) => {
							if (bigValue < element.year) {
								bigValue = element.year
							}
						})
						this.addform.year = bigValue + 1 //默认值为账簿年度最大值+1。 yyyy
						this.addform.year = new Date(this.addform.year + '-01-01')
					} else {
						//账簿列表为空时
						this.addform.year = new Date() //默认为系统当前年度
						// this.$set(this.addform, 'year', new Date().Format('yyyy'))
						this.addform.yearSubject = '0' //默认为“初始化数据”
						this.addform.yearAbstract = '0' //默认为“初始化数据”
					}
				}
			}, 200)
			// if (!v) this.addform = this.$cu.deepClone(addform)
			// if (!v) this.editform = this.$cu.deepClone(editform)
		},
		// 添加科目表单验证
		onOkadd() {
			this.$refs['formValidateAdd'].validate((valid) => {
				if (valid) {
					this.$nextTick(() => {
						this.addAccountBookApi() // 添加账簿 接口
					})
				}
			})
		},
		// 账簿年度选择器改变回调
		dataPickerChange(valueData) {
			this.addform.year = valueData
		},
		selectModelChange1() {
			//  this.addform.yearSubject
		},
		selectModelChange2() { }
	}
}
</script>
<style lang="less" scoped>
.topBody {
	display: flex;
	padding-top: 20px;
	align-items: center;
	flex-wrap: wrap;

	.topBodyItem {
		margin-right: 12px;
		margin-bottom: 20px;
		display: flex;
    	align-items: center;
		.itemSpan {
			white-space: nowrap;
			width: 80px;
			text-align: right;
			font-size: 14px;
			color: rgba(0, 0, 0, 0.85) !important;
			margin-right: 10px;
		}

		.itemImport {
			width: 200px;
		}
	}
}
</style>
